document.getElementById('forgot-password-form').addEventListener('submit', function(event) {
    event.preventDefault();
    const email = document.getElementById('email').value.trim();
    const code = document.getElementById('code').value.trim();

    if (!email) {
        alert('请输入邮箱');
        return;
    }
    if (!code) {
        alert('请输入邮箱验证码');
        return;
    }

    // 验证邮箱和验证码
    fetch('/api/user/code/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ code, email })
    })
    .then(res => res.json())
    .then(result => {
        if (result.code === 200) {
            // 验证成功，显示重置密码框
            showResetPasswordBox(email);
        } else {
            alert(result.message || '验证码错误');
        }
    })
    .catch(() => {
        alert('请求失败，请重试');
    });
});

// 显示重置密码输入框（页面内）
function showResetPasswordBox(email) {
    // 如果已存在则不重复添加
    if (document.getElementById('reset-password-area')) return;
    const container = document.querySelector('.login-container');
    const area = document.createElement('div');
    area.id = 'reset-password-area';
    area.innerHTML = `
        <div class="input-group">
            <label for="new-password">新密码</label>
            <input type="password" id="new-password" placeholder="请输入新密码">
        </div>
        <div class="input-group">
            <label for="confirm-password">确认新密码</label>
            <input type="password" id="confirm-password" placeholder="请再次输入新密码">
        </div>
        <button id="submit-reset-password">提交</button>
    `;
    container.appendChild(area);
    // 禁用表单
    document.getElementById('forgot-password-form').style.display = 'none';
    document.getElementById('submit-reset-password').onclick = function() {
        const password = document.getElementById('new-password').value.trim();
        const confirm = document.getElementById('confirm-password').value.trim();
        if (!password || !confirm) {
            alert('请输入新密码并确认');
            return;
        }
        if (password !== confirm) {
            alert('两次输入的密码不一致');
            return;
        }
        // 从 sessionStorage.token 解码 jwt 获取 id
        let id = 1;
        try {
            const token = sessionStorage.getItem('token');
            if (token) {
                const payload = JSON.parse(atob(token.split('.')[1]));
                if (payload && payload.id) id = payload.id;
            }
        } catch (e) {}
        fetch('/api/user/insert', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ email, password, id })
        })
        .then(res => res.json())
        .then(result => {
            if (result.code === 200) {
                alert('密码重置成功，请返回登录');
                window.location.href = 'login.html';
            } else {
                alert(result.message || '密码重置失败');
            }
        })
        .catch(() => {
            alert('请求失败，请重试');
        });
    };
}
// 发送验证码按钮逻辑
document.getElementById('sendCodeBtn').addEventListener('click', function() {
    const email = document.getElementById('email').value.trim();
    if (!email) {
        alert('请先输入邮箱');
        return;
    }
    const btn = this;
    btn.disabled = true;
    btn.textContent = '发送中...';
    fetch(`/api/user/send/${encodeURIComponent(email)}`)
        .then(res => res.json())
        .then(result => {
            if (result.code === 200) {
                alert('验证码已发送，请查收邮箱');
                let sec = 60;
                btn.textContent = `重新发送(${sec})`;
                const timer = setInterval(() => {
                    sec--;
                    btn.textContent = `重新发送(${sec})`;
                    if (sec <= 0) {
                        clearInterval(timer);
                        btn.disabled = false;
                        btn.textContent = '发送验证码';
                    }
                }, 1000);
            } else {
                alert(result.message || '发送失败');
                btn.disabled = false;
                btn.textContent = '发送验证码';
            }
        })
        .catch(() => {
            alert('发送失败，请重试');
            btn.disabled = false;
            btn.textContent = '发送验证码';
        });
});